package com.moefor.olive_branch.repository;

import com.moefor.olive_branch.entity.Project;
import org.hibernate.jpa.criteria.OrderImpl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import javax.persistence.criteria.*;
import java.util.List;

@Repository
public interface ProjectRepository extends CrudRepository<Project,Integer>,JpaSpecificationExecutor<Project> {

    Page<Project> findByTitleLikeOrderByCreateTimeDesc(String keyword, Pageable pageable);

    Page<Project> findAllByOrderByCreateTimeDesc(Pageable pageable);

    default Page<Project> findAllByTitleLikeOrderByCreateTimeDesc(List<String> titleList, PageRequest pageRequest){
        return findAll(new Specification<Project>() {
            @Override
            public Predicate toPredicate(Root<Project> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Expression<String> titlePath = root.get("title").as(String.class);
                Predicate predicate = null;
                if (!CollectionUtils.isEmpty(titleList)) {
                    predicate = criteriaBuilder.or(criteriaBuilder.like(titlePath, "%" + titleList.get(0) + "%"));
                    for (int i = 1; i < titleList.size(); i++) {
                        predicate = criteriaBuilder.or(predicate, criteriaBuilder.like(titlePath, "%" + titleList.get(i) + "%"));
                    }
                }
                predicate = criteriaBuilder.and(predicate, criteriaBuilder.equal(root.get("state").as(Project.State.class), Project.State.ALLOW));
                criteriaQuery.where(predicate);
                criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createTime").as(Integer.class)));
                return criteriaQuery.getRestriction();
            }
        }, pageRequest);
    }
}

